package top.martinzh.stock.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import top.martinzh.stock.entity.Company;
import top.martinzh.stock.entity.Trade;
import top.martinzh.stock.entity.TradeStateEnum;
import top.martinzh.stock.entity.TradeType;

/**
 * 交易管理
 * @author martin
 *
 */
@Service
public class TradeManager {
	// 参考资料： https://wiki.mbalib.com/wiki/%E8%BF%9E%E7%BB%AD%E7%AB%9E%E4%BB%B7
	@Autowired
	private CompanyManager companyManager;
	
	 private Map<String, List<Trade>> marketMap = new HashMap<>();
	
	/**
	 * 买股票
	 * @param code 股票代码
	 * @param price 股票价格
	 * @param amount 交易数量
	 */
	public Trade buy(String code, double price, int amount) {
		
		List<Trade> list = marketMap.get(code);

		Trade trade = new Trade();
		trade.setId(System.currentTimeMillis() + "");
		Company company = companyManager.getByCode(code).orElseGet(null);
		trade.setCompany(company);
		trade.setPrice(price);
		trade.setAmount(amount);
		trade.setTradeType(TradeType.BUY);
		
		if (list == null) {
			list = new ArrayList<>();
			marketMap.put(code, list);
		}
		if (list.isEmpty()) {
			// 第一次交易
			if (price > company.getIssuePrice()) {
				trade.setState(TradeStateEnum.DONE);
			}
			// 更新成交价
			company.setCurrentPrice(trade.getPrice());
		} else {
			// 查找卖出交易中，卖出价格小于买入价的交易单
			list.stream().filter( e-> 
				e.getState() == TradeStateEnum.DELEGATING	// 正在委托
				&& e.getTradeType() == TradeType.SELL 	// 卖出交易
				&& e.getPrice() <= price //  卖出价格小于买入价
				).sorted((a, b)-> {
					return (int) ( a.getPrice() - b.getPrice() );
				}).forEachOrdered(t->{
					// 成交
					t.setState(TradeStateEnum.DONE);
					// 更新成交价
					company.setCurrentPrice(trade.getPrice());
				});
		}
		
		
		list.add(trade);
		return trade;
	}
	
	/**
	 * 卖股票
	 * @param code 股票代码
	 * @param price 股票价格
	 * @param amount 交易数量
	 */
	public void sell(String code, double price, int amount) {
		List<Trade> list = marketMap.get(code);
		if (list == null) {
			list = new ArrayList<>();
		}
	}
	
}
